<template>
  <!-- 内容 -->
  <div class="main">
    <div class="container">
        <div class="position-relative">
        <!-- 筛选条件 -->
        <ul class="nav nav-tabs mb-3">
            <li class="nav-item">
            <span class="nav-link" :class="{active: orderMode == 0}" @click="changeOrderMode(0)">最新</span>
            </li>
            <li class="nav-item">
            <span class="nav-link" :class="{active: orderMode == 1}" @click="changeOrderMode(1)">最热</span>
            </li>
        </ul>
        <button type="button" class="btn btn-primary btn-sm position-absolute rt-0" data-toggle="modal" data-target="#publishModal" v-if="isLogined">我要发布</button>
        </div>
        <!-- 弹出框 -->
        <div class="modal fade" id="publishModal" tabindex="-1" role="dialog" aria-labelledby="publishModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="publishModalLabel">新帖发布</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                <div class="form-group">
                    <label for="recipient-name" class="col-form-label">标题：</label>
                    <input type="text" class="form-control" id="recipient-name" v-model="postForm.title">
                </div>
                <div class="form-group">
                    <label for="message-text" class="col-form-label">正文：</label>
                    <textarea class="form-control" id="message-text" rows="15" v-model="postForm.content" />
                </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal" @click="cancelPublish">取消</button>
                <button type="button" class="btn btn-primary" id="publishBtn" @click="publish">发布</button>
            </div>
            </div>
        </div>
        </div>
        <!-- 提示框 -->
        <div class="modal fade" id="hintModal" tabindex="-1" role="dialog" aria-labelledby="hintModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="hintModalLabel">提示</h5>
            </div>
            <div class="modal-body" id="hintBody">
                发布完毕!
            </div>
            </div>
        </div>
        </div>
        <!-- 帖子列表 -->
        <ul class="list-unstyled">
          <li class="media pb-3 pt-3 mb-3 border-bottom" v-for="discussPost in discussPosts" :key="discussPost.post.id">
              <a :href="'/profile/' + discussPost.user.id">
              <img :src="discussPost.user.headerUrl" class="mr-4 rounded-circle" alt="用户头像" style="width:50px;height:50px;">
              </a>
              <div class="media-body">
              <h6 class="mt-0 mb-3">
                  <router-link :to="'discuss/detail/' + discussPost.post.id">{{ discussPost.post.title }}</router-link>
                  <span class="badge badge-secondary bg-primary" v-if="discussPost.post.type == 1">置顶</span>
                  <span class="badge badge-secondary bg-danger" v-if="discussPost.post.status == 1">精华</span>
              </h6>
              <div class="text-muted font-size-12">
                  <u class="mr-3">{{ discussPost.user.username }}</u> 发布于 <b>{{ discussPost.post.createTime }}</b>
                  <ul class="d-inline float-right">
                  <li class="d-inline ml-2">
                    <b v-if="discussPost.like?.status == 1">已</b>赞 <i v-if="discussPost.like">{{ discussPost.like.count }}</i>
                  </li>
                  <li class="d-inline ml-2">|</li>
                  <li class="d-inline ml-2">回帖 {{ discussPost.post.commentCount }}</li>
                  </ul>
              </div>
              </div>
          </li>
        </ul>
        <!-- 分页 -->
        <div class="mt-5" v-if="discussPosts.length > 0">
          <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="pageSizes"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          />
        </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/store/modules/user'
import DiscussPost from '@/api/discussPost'
import Like from '@/api/like'

const userStore = useUserStore()

const isLogined = ref(false)

const orderMode = ref(0)

const discussPosts = ref([])

const small = ref(false)
const background = ref(false)
const disabled = ref(false)

const total = ref(10)
const pageSizes = ref([10, 20, 50, 100])
const currentPage = ref(1)
const pageSize = ref(10)

const postForm = ref({
  title: '',
  content: ''
})

const postMsg = ref('')

onMounted(async () => {
  if (userStore.username != 'nowcoder') {
    isLogined.value = true
  }
  getDiscussPosts()
})

const subscribe = userStore.$subscribe(
  (mutation, state) => {
    /*
      * mutation主要包含三个属性值：
      *   events：当前state改变的具体数据，包括改变前的值和改变后的值等等数据
      *   storeId：是当前store的id
      *   type：用于记录这次数据变化是通过什么途径，主要有三个分别是
      *         “direct” ：通过 action 变化的
                ”patch object“ ：通过 $patch 传递对象的方式改变的
                “patch function” ：通过 $patch 传递函数的方式改变的
      *
      * */
    // 在此处监听store中值的变化，当变化为某个值的时候，做一些业务操作
    () => {
      if (userStore.username != 'nowcoder') {
        console.log('登录状态')
        isLogined.value = true
      } else {
        console.log('未登录状态')
        isLogined.value = false
      }
    }
  },
  { detached: false }
)

const getDiscussPosts = async () => {
  DiscussPost.getDiscussPosts(currentPage.value, pageSize.value, orderMode.value)
  .then(res => {
    getTotal()
    discussPosts.value = res
    for (let i in discussPosts.value) {
      discussPosts.value[i].like = {
        count: 0,
        status: 0
      }
      getLikeCount(discussPosts.value[i].post.id)
      getLikeStatus(discussPosts.value[i].post.id)
    }
  })
}

const getTotal = async () => {
  DiscussPost.getTotal().then(res => {
    total.value = res
  })
}

const changeOrderMode = async (mode) => {
  orderMode.value = mode
  getDiscussPosts()
}

const handleSizeChange = async () => {
  getDiscussPosts()
}

const handleCurrentChange = async () => {
  getDiscussPosts()
}

const publish = async () => {
  DiscussPost.addDiscussPost(postForm.value.title, postForm.value.content)
  .catch(() => {
    postMsg.value = '帖子格式不正确'
  })

  $("#publishModal").modal("hide")
  $("#hintModal").modal("show")
  setTimeout(async () => {
    // 刷新页面
    getDiscussPosts()
    $("#hintModal").modal("hide")
  }, 1000)
}

const cancelPublish = () => {
  postForm.value.title = ''
  postForm.value.content = ''
}

const getLikeCount = async (entityId) => {
  Like.getLikeCount(1, entityId)
  .then(async res => {
    // 刷新状态
    for (let i in discussPosts.value) {
      if (entityId == discussPosts.value[i].post.id) {
        discussPosts.value[i].like.count = res
        break
      }
    }
  })
}

const getLikeStatus = async (entityId) => {
  Like.getLikeStatus(1, entityId)
  .then(async res => {
    // 刷新状态
    for (let i in discussPosts.value) {
      if (entityId == discussPosts.value[i].post.id) {
        discussPosts.value[i].like.status = res
        break
      }
    }
  })
}

</script>

<style scoped>

</style>
